import Sprite from '../../../base/sprite';
import { SCREEN_WIDTH } from '../../../render';

const BULLET_IMG_SRC = 'images/bullet.png';
const BULLET_WIDTH = 16;
const BULLET_HEIGHT = 30;

export default class TiaoBullet extends Sprite {

  constructor() {
    super(BULLET_IMG_SRC, BULLET_WIDTH, BULLET_HEIGHT);
    this.rotation = 0;
  }

  init(x, y, speed, damage, penetration, targetX, targetY) {
    this.id = Math.random().toString(36).substr(2, 9);
    this.x = x;   // 初始位置
    this.y = y;
    this.speed = speed;
    this.damage = damage;
    this.penetration = penetration; // 穿透
    this.isActive = true;
    this.visible = true;

    this.dx = targetX - this.x;
    this.dy = targetY - this.y;
    this.distance = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
    // 计算子弹偏转角度
    this.rotation = Math.atan2(this.dy, this.dx) + Math.PI / 2; // 加上Math.PI/2是因为子弹图片默认是朝上的
  }

  // 重写 sprite 的 render 方法，支持旋转绘制
  render(ctx) {
    if (!this.visible) return;

    ctx.save(); // 保存当前画布状态
    ctx.translate(this.x + this.width / 2, this.y + this.height / 2); // 将画布原点移动到子弹中心
    ctx.rotate(this.rotation); // 旋转画布
    ctx.drawImage(
      this.img,
      -this.width / 2,
      -this.height / 2,
      this.width,
      this.height
    ); // 在旋转后的坐标系中绘制子弹
    ctx.restore(); // 恢复画布状态
  }

  // 每一帧更新子弹位置
  update() {
    if (GameGlobal.databus.isGameOver) {
      return;
    }

    if (this.distance > 0) {
      this.x += (this.dx / this.distance) * this.speed;
      this.y += (this.dy / this.distance) * this.speed;
    }

    // 超出屏幕外销毁
    if (this.y < -this.height || this.x < -this.width || this.x > SCREEN_WIDTH) {
      this.destroy();
    }
  }

  destroy() {
    this.isActive = false;
    // 子弹没有销毁动画，直接移除
    this.remove();
  }

  remove() {
    this.isActive = false;
    this.visible = false;
    // 回收子弹对象
    GameGlobal.databus.removeBullets(this);
  }
}
